//
//  BTEHomeViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit

class BTEProductFoureViewController: BTEBaseViewController {
    
    var time: Date?
    
    let server = BTEProductToolNetServer()
    
    var model: BTEProductpeeebonbloidNetModel?
    
    var listmodel: BTECarnepalaeoglacfewfewiologyNetModel? {
        didSet {
            guard let m = listmodel else {
                return
            }
            v.model = m.gena
        }
    }
    
    var pid: String?
    
    var v: BTEProductFoureView {
        return view as! BTEProductFoureView
    }
    
    override func loadView() {
        view = BTEProductFoureView()
    }

    init(model: BTEProductpeeebonbloidNetModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        time = Date()
        
        titleLabel.text = model?.aftermath ?? ""
        
        v.list.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(navigationBar.snp.bottom)
            make.bottom.equalTo(v.button.snp.top)
        }
        
        v.list.isHidden = true
        v.button.isHidden = true
        
        load()
        
        v.button.addTarget(self, action: #selector(push), for: .touchUpInside)
        
        v.clickChoise = {[weak self] idx in
            DispatchQueue.main.async {
                BTEContactManager.shared.requestContactAccess { re in }
            }

            BTEContactManager.shared.presentContactPickerUI()
            BTEContactManager.shared.onContactSelected = {[weak self] m in
                self?.listmodel?.gena?[idx].manificum = "\(m.firstName) \(m.lastName)"
                self?.listmodel?.gena?[idx].meedful = m.phone
                self?.v.list.reloadRows(at: [IndexPath.init(row: idx, section: 0)], with: .none)
            }
        }
        
    }

}



extension BTEProductFoureViewController {
    
    @objc func load(){
        BTEHUD.shared.showLoader(on: view)
        server.belaud(data: ["privileger":pid!]) {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                self?.v.list.isHidden = false
                self?.v.button.isHidden = false
                
                success?.sidelingwise?.gena?.forEach { item in
                    item.panderism?.forEach({$0.choised = false})
                    item.panderism?.filter({$0.dikegrave == item.anhydridization}).first?.choised = true
                }

                self?.listmodel = success?.sidelingwise
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
    @objc func push(){
        view.endEditing(true)
        var lists: [String:String] = [:]
        
        var list_a : [[String:String]] = []
        
        listmodel?.gena?.forEach { item in
            var list_b : [String:String] = [:]
            list_b["anhydridization"] = item.anhydridization ?? ""
            list_b["manificum"] = item.manificum ?? ""
            list_b["meedful"] = item.meedful ?? ""
            list_a.append(list_b)
        }
        
        
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: list_a, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                lists["sidelingwise"] = jsonString
                lists["privileger"]  = pid!
                BTEHUD.shared.showLoader(on: view)
                server.compute(data:lists) {[weak self] result in
                    switch result {
                    case .success(let success):
                        BTEHUD.shared.hide()
                        let t = TrackingEvent.init(step: "6", startTimestamp: "\((self?.time)!.timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)")
                        BTELocationReporterManager.shared.reportLocation(for: t)
                        self?.navigationController?.popViewController(animated: true)
                        break
                    case .failure(let failure):
                        switch failure {
                        case .Error(c: let b, m: let bd):
                            BTEHUD.shared.showError(bd, on: (self?.view)!)
                            break
                        default:
                            break
                        }
                        break
                    }
                }
            }
        } catch {
            print("user connection json error")
        }
    }
    
}
